#region license
# This file is part of Grawlix.
# 
# Grawlix is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as
# published by the Free Software Foundation, either version 3 of
# the License, or (at your option) any later version.
# 
# Grawlix is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public
# License along with Grawlix.  If not, see
# <http://www.gnu.org/licenses/>.
#endregion

"""Generic synchronization constructions."""

namespace ConcurrentBoo
import System.Threading

static class Sync:
"""Synchronization primitives."""

	# FIXME: Boo regression.
	def Cas(ref location as int, compare as int, data as int):
	"""
	Atomic compare and swap operation.
	Param location: Variable to change.
	Param compare: Only change location if location == compare.
	Param data: What to store in location.
	Returns: true if change took place
	"""
		if Thread.VolatileRead(location) == compare:
			Thread.VolatileWrite(location, data)
			return true
		return false
	#	return (Interlocked.CompareExchange(location,
	#	                                    data,
	#	                                    compare) == compare)
	
	# FIXME: When generic support is in.
	/*
	def Cas[of T](ref location as T, compare as T, data as T):
	"""
	Atomic compare and swap operation.
	Param location: Variable to change.
	Param compare: Only change location if location is compare.
	Param data: What to store in location.
	Returns: true if change took place
	"""
		return (Interlocked.CompareExchange(location,
		                                    data,
		                                    compare) == compare)
	*/
	
	# FIXME: Boo regression.
	def Swap(ref location as int, data as int):
	"""
	Atomic swap.
	Param location: Variable to change.
	Param data: What to store in location.
	Returns: Old value in location.
	"""
		old = Thread.VolatileRead(location)
		Thread.VolatileWrite(location, data)
		return old
	#	return Interlocked.Exchange(location, data)
	
	# FIXME: When generic support is in.
	/*
	def Swap[of T(class)](ref location as T, data as T):
	"""
	Atomic swap.
	Param location: Variable to change.
	Param data: What to store in location.
	Returns: Old value in location.
	"""
		return Interlocked.Exchange(location, data)
	*/
	
